/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhies.desktop.activity.editor;

import com.kungkhies.desktop.activity.explorer.ActivityExplorerTopComponent;
import com.kungkhies.desktop.library.entities.Activity;
import java.io.IOException;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openide.util.Exceptions;
import org.openide.util.LookupEvent;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.NotifyDescriptor.Confirmation;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.UndoRedo;
import org.openide.cookies.SaveCookie;
import org.openide.explorer.ExplorerManager;
import org.openide.util.Lookup;
import org.openide.util.LookupListener;
import org.openide.util.RequestProcessor;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//com.kungkhies.desktop.activity.editor//ActivityEditor//EN",
autostore = false)
@TopComponent.Description(preferredID = "ActivityEditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.kungkhies.desktop.activity.editor.ActivityEditorTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ActivityEditorAction",
preferredID = "ActivityEditorTopComponent")
public final class ActivityEditorTopComponent extends TopComponent implements ExplorerManager.Provider, LookupListener
{
    private static ExplorerManager em = new ExplorerManager();
    private Activity activity;
    private UndoRedo.Manager manager = new UndoRedo.Manager();
    private final SaveCookieImpl impl;
    private final InstanceContent content;
    private Lookup.Result result = null;

    public ActivityEditorTopComponent()
    {
        initComponents();
        setName(NbBundle.getMessage(ActivityEditorTopComponent.class, "CTL_ActivityEditorTopComponent"));
        setToolTipText(NbBundle.getMessage(ActivityEditorTopComponent.class, "HINT_ActivityEditorTopComponent"));

        nameTextField.getDocument().addUndoableEditListener(manager);
        descriptionTextArea.getDocument().addUndoableEditListener(manager);
        urlTextField.getDocument().addUndoableEditListener(manager);

        nameTextField.getDocument().addDocumentListener(new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void removeUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void changedUpdate(DocumentEvent arg0)
            {
                fire(true);
            }
        });

        descriptionTextArea.getDocument().addDocumentListener(new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void removeUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void changedUpdate(DocumentEvent arg0)
            {
                fire(true);
            }
        });

        urlTextField.getDocument().addDocumentListener(new DocumentListener()
        {
            @Override
            public void insertUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void removeUpdate(DocumentEvent arg0)
            {
                fire(true);
            }

            @Override
            public void changedUpdate(DocumentEvent arg0)
            {
                fire(true);
            }
        });

        //Create a new instance of our SaveCookie implementation:
        impl = new SaveCookieImpl();

        //Create a new instance of our dynamic object:
        content = new InstanceContent();

        //Add the dynamic object to the TopComponent Lookup:
        associateLookup(new AbstractLookup(content));

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        activityEditorTitleLabel = new javax.swing.JLabel();
        nameLabel = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        descriptionLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        descriptionTextArea = new javax.swing.JTextArea();
        assIncludedCheckBox = new javax.swing.JCheckBox();
        urlLabel = new javax.swing.JLabel();
        urlTextField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setFont(new java.awt.Font("Arial", 1, 10)); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(activityEditorTitleLabel, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.activityEditorTitleLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(nameLabel, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.nameLabel.text")); // NOI18N

        nameTextField.setText(org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.nameTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(descriptionLabel, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.descriptionLabel.text")); // NOI18N

        descriptionTextArea.setColumns(20);
        descriptionTextArea.setRows(5);
        jScrollPane1.setViewportView(descriptionTextArea);

        org.openide.awt.Mnemonics.setLocalizedText(assIncludedCheckBox, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.assIncludedCheckBox.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(urlLabel, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.urlLabel.text")); // NOI18N

        urlTextField.setText(org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.urlTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.saveButton.text")); // NOI18N
        saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveButtonMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(ActivityEditorTopComponent.class, "ActivityEditorTopComponent.cancelButton.text")); // NOI18N
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(73, 73, 73)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(urlLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(assIncludedCheckBox)
                        .addComponent(jScrollPane1)
                        .addComponent(descriptionLabel)
                        .addComponent(nameLabel)
                        .addComponent(activityEditorTitleLabel)
                        .addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
                        .addComponent(urlTextField)))
                .addContainerGap(172, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(activityEditorTitleLabel)
                .addGap(61, 61, 61)
                .addComponent(nameLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43)
                .addComponent(descriptionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(56, 56, 56)
                .addComponent(assIncludedCheckBox)
                .addGap(50, 50, 50)
                .addComponent(urlLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(urlTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(101, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_cancelButtonMouseClicked
    {//GEN-HEADEREND:event_cancelButtonMouseClicked
        clearAndCancel();
    }//GEN-LAST:event_cancelButtonMouseClicked

    private void saveButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_saveButtonMouseClicked
    {//GEN-HEADEREND:event_saveButtonMouseClicked
        try
        {
            impl.save();
        }
        catch (IOException ex)
        {
            Exceptions.printStackTrace(ex);
        }
        ActivityExplorerTopComponent.refreshNode();
    }//GEN-LAST:event_saveButtonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel activityEditorTitleLabel;
    private javax.swing.JCheckBox assIncludedCheckBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JTextArea descriptionTextArea;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel urlLabel;
    private javax.swing.JTextField urlTextField;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened()
    {
        RequestProcessor.getDefault().post(new Runnable()
        {
            @Override
            public void run()
            {
                readActivity();
            }
        });
    }

    @Override
    public void componentClosed()
    {
        result.removeLookupListener(this);
        result = null;
    }
    
    private void readActivity()
    {
        //JavaDBSupport.ensureStartedDB();
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                TopComponent tc = WindowManager.getDefault().findTopComponent("ActivityExplorerTopComponent");
                if (tc == null)
                {
                    System.out.println("Activity Viewer. readActivity: top component in get default is null");
                    return;
                }
                result = tc.getLookup().lookupResult(Activity.class);
                result.addLookupListener(ActivityEditorTopComponent.this);
                resultChanged(new LookupEvent(result));
            }
        });
    }

    void writeProperties(java.util.Properties p)
    {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p)
    {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager()
    {
        return em;
    }

    @Override
    public void resultChanged(LookupEvent le)
    {
        Lookup.Result r = (Lookup.Result) le.getSource();
        Collection<Activity> coll = (Collection<Activity>) r.allInstances();
        if (!coll.isEmpty())
        {
            for (Activity ac : coll)
            {
                activity = ac;
                String name = ac.getName();
                String ass = ac.getAssessment();
                if (ass == null || ass.equals("false"))
                {
                    assIncludedCheckBox.setSelected(false);
                }
                else
                    if (ass.equals("true"))
                    {
                        assIncludedCheckBox.setSelected(true);
                    }
                else
                    {
                        assIncludedCheckBox.setSelected(false);   
                    }
                
                
                nameTextField.setText(name);
                descriptionTextArea.setText(ac.getDescription());
                urlTextField.setText(ac.getUrl());           
            }
        }
        else
        {
            nameTextField.setText("");
            descriptionTextArea.setText("");
            urlTextField.setText("");   
        }
    }

    private class SaveCookieImpl implements SaveCookie
    {
        @Override
        public void save() throws IOException
        {

            Confirmation message = new NotifyDescriptor.Confirmation("Do you want to save \""
                    + nameTextField.getText() + "\"?",
                    NotifyDescriptor.OK_CANCEL_OPTION,
                    NotifyDescriptor.QUESTION_MESSAGE);

            Object result = DialogDisplayer.getDefault().notify(message);

            //When user clicks "Yes", indicating they really want to save,
            //we need to disable the Save button and Save menu item,
            //so that it will only be usable when the next change is made
            //to the text field:
            if (NotifyDescriptor.YES_OPTION.equals(result))
            {
                fire(false);
                EntityManager entityManager = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU").createEntityManager();
                entityManager.getTransaction().begin();
                if (activity.getActivityId() != null)
                {
                    Activity c = entityManager.find(Activity.class, activity.getActivityId());
                    c.setName(nameTextField.getText());
                    c.setDescription(descriptionTextArea.getText());
                    c.setUrl(urlTextField.getText());
                    c.setAssessment(Boolean.toString(assIncludedCheckBox.isSelected()));
                    entityManager.getTransaction().commit();
                }
                else
                {
                    activity.setName(nameTextField.getText());
                    activity.setDescription(descriptionTextArea.getText());
                    activity.setUrl(urlTextField.getText());
                    activity.setAssessment(Boolean.toString(assIncludedCheckBox.isSelected()));
                    entityManager.persist(activity);
                    entityManager.getTransaction().commit();
                }
                ActivityExplorerTopComponent.refreshNode();
            }
        }
    }

    public void fire(boolean modified)
    {
        if (modified)
        {
            //If the text is modified,
            //we add SaveCookie impl to Lookup:
            content.add(impl);
        }
        else
        {
            //Otherwise, we remove the SaveCookie impl from the lookup:
            content.remove(impl);
        }
    }
    
    public void clearAndCancel()
    {
       nameTextField.setText("");
       descriptionTextArea.setText("");
       urlTextField.setText(""); 
       assIncludedCheckBox.setSelected(false);
       this.close();
    }
}